﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace ChestPainCenterSystem.Code.Utils
{
    public static class ImageHelper
    {
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <param name="maxHeight">最大高度</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <returns></returns>
        public static Stream Thumbnail(this Stream stream, int maxHeight = 900, int maxWidth = 900)
        {

            Image originBitmap = Image.FromStream(stream);
            MemoryStream result = new MemoryStream();
            var ow = originBitmap.Width;
            var oh = originBitmap.Height;
            int h = 0;
            int w = 0;
            double multiple = 1;
            if (ow >= oh && ow >= maxWidth)
            {
                multiple = (double)maxWidth / (double)ow;
            }
            else if (ow <= oh && oh >= maxHeight)
            {
                multiple = (double)maxWidth / (double)ow;
            }
            h = Convert.ToInt32(oh * multiple);
            w = Convert.ToInt32(ow * multiple);
            using (var newImage = new Bitmap(w, h))
            {
                using (var graphic = GetGraphic(originBitmap, newImage))
                {
                    graphic.DrawImage(originBitmap, 0, 0, w, h);
                    using (var encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                        newImage.Save(result, ImageFormat.Jpeg);
                    }
                }
            }
            return result;
        }
        private static Graphics GetGraphic(Image originImage, Bitmap newImage)
        {
            newImage.SetResolution(originImage.HorizontalResolution, originImage.VerticalResolution);
            var graphic = Graphics.FromImage(newImage);
            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            return graphic;
        }
    }
}